/**
 * @desc 事件的订阅/发布模式
 */
// 判断对象是否是字符串
function isString (obj) {
  return Object.prototype.toString.call(obj) === '[object String]'
}
// 判断对象是否为function
function isFunction (fn) {
  return Object.prototype.toString.call(fn) === '[object Function]'
}

class SelfEvent {
  constructor () {
    this.subs = {}
  }
  clear () {
    this.subs = {}
  }
  on (eventName, callback) {
    if (!eventName) {
      throw new Error('eventName cannot be empty')
    } else if (!isString(eventName)) {
      throw new Error('eventName must be a string')
    } else if (!callback) {
      throw new Error('callback cannot be empty')
    } else if (!isFunction(callback)) {
      throw new Error('eventName must be a func')
    }
    if (!this.subs[eventName]) {
      this.subs[eventName] = []
    }
    this.subs[eventName].push(callback)
  }
  emit (eventName, ...params) {
    if (!eventName) {
      throw new Error('eventName cannot be empty')
    } else if (!isString(eventName)) {
      throw new Error('eventName must be a string')
    }
    if (!this.subs[eventName]) {
      return
    }
    this.subs[eventName].forEach((func) => {
      func(...params)
    })
  }
  once (eventName, callback) {
    if (!eventName) {
      throw new Error('eventName cannot be empty')
    } else if (!isString(eventName)) {
      throw new Error('eventName must be a string')
    } else if (!callback) {
      throw new Error('callback cannot be empty')
    } else if (!isFunction(callback)) {
      throw new Error('eventName must be a func')
    }
    this.subs[eventName] = [callback]
  }
}

export default SelfEvent
